/**
 * 通用js方法和变量
 */

const baseURL = process.env.VUE_APP_BASE_API

import { formatMoney } from 'accounting/accounting.js'

// 千位小数分隔
const divideMoney = (num, decimal, isEdit) => {
  if (decimal === 6 && isEdit) num = num / 10000
  return formatMoney(num, {
    symbol: '', // 符号($/￥)
    decimal: '.', // 小数点
    thousand: ',', // 分隔符
    precision: decimal, // 小数位
    format: '%s%v'
  })
}

// 日期格式化
const parseTime = function(time, pattern) {
  if (arguments.length === 0) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 表单重置
const resetForm = function(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}

// 回显数据字典
const selectDictLabel = function(datas, value) {
  let actions = []
  if (datas && datas.length && value) actions = datas.filter(item => item.dictValue === value)
  if (actions && actions.length) return actions[0].dictLabel

  // var actions = []
  // Object.keys(datas).map((key) => {
  //   if (datas[key].dictValue === (value)) {
  //     actions.push(datas[key].dictLabel)
  //     return false
  //   }
  // })
  // return actions.join('')
}
// 通用下载方法
export function download(fileName) {
  window.location.href = baseURL + '/common/download?fileName=' + encodeURIComponent(fileName) + '&delete=' + true
}

// 用户下载方法
const downloadUser = function(fileName, isTemp) {
  window.location.href = baseURL + '/common/download?fileName=' + encodeURIComponent(fileName) + '&delete=' + isTemp
}

// 添加日期范围
const changeDateRange = function(filters, dateRange) {
  const search = filters
  if (dateRange != null && dateRange !== '' && dateRange.length > 0) {
    const data = dateRange.toString()
    search.dateRange = data
  } else {
    search.dateRange = ''
  }
  return search
}

// 遍历树形结构的数据 当children节点为空的时候，删除children节点 liangyaxin
const deleteChildren = function(nodeData) {
  var childs = nodeData
  if (nodeData !== undefined && nodeData !== '' && nodeData !== null && nodeData.length > 0) {
    nodeData.forEach(item => {
      if ('children' in item) {
        if (item.children === null || item.children === '' || item.children.length === 0) {
          delete item.children
        } else if (item.children.length > 0) {
          this.deleteChildren(item.children, item)
        }
      }
    })
  }
  return childs
}
/**
 * 实现思路: 前台去后台查找下载的信息
 *          后台返回下载地址
 *          调次方法下载
 * @param {*} obj  后台返回下载的地址
 * @param {*} name  下载文件的名称
 * @param {*} suffix 下载文件的格式
 */
const downloadFile = function(obj, name, suffix) {
  const url = window.URL.createObjectURL(new Blob([obj]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 实现思路: 前台去后台查找下载的信息
 *          后台返回文件流
 *          调次方法下载
 * @param {*} obj  后台返回下载文件的文件流
 * @param {*} fileName  下载文件的名称
 * @param {*} type  下载文件的类型
 */
const downloadFileFlow = function(obj, fileName, type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"') {
  const blob = new Blob([obj], { type })
  const link = document.createElement('a')
  link.style.display = 'none'
  link.setAttribute('download', `${fileName}-${new Date()
    .toLocaleString('zh-Hans-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
    .replace(/\:/g, '')}.xlsx`)
  link.href = URL.createObjectURL(blob)
  document.body.appendChild(link)
  link.click()
  URL.revokeObjectURL(link.href)
  document.body.removeChild(link)
}

const downloadFileFlowPdf = function(obj, fileName, type = 'application/pdf;charset=UTF-8') {
  const blob = new Blob([obj], { type })
  const link = document.createElement('a')
  link.style.display = 'none'
  link.setAttribute('download', fileName)
  link.href = URL.createObjectURL(blob)
  document.body.appendChild(link)
  link.click()
  URL.revokeObjectURL(link.href)
  document.body.removeChild(link)
}

// 表格行加颜色
const tableRowClassName = function({ row, rowIndex }) {
  return 'row' + rowIndex
}

// 计算时间差
const GetDateDiff = function(startTime, endTime) {
  startTime = startTime.replace(/\-/g, '/')
  endTime = endTime.replace(/\-/g, '/')
  var date1 = new Date(startTime) // 开始时间
  var date2 = new Date(endTime) // 结束时间
  var date3 = date2.getTime() - date1.getTime()
  // 计算出相差天数
  var days = Math.floor(date3 / (24 * 3600 * 1000))
  // 计算出小时数
  var leave1 = date3 % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000))
  // 计算相差分钟数
  var leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000))
  // 计算相差秒数
  var leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
  var seconds = Math.round(leave3 / 1000)
  return days + '天 ' + hours + '小时 ' + minutes + ' 分钟' + seconds + ' 秒'
}

const common = {
  parseTime,
  resetForm,
  selectDictLabel,
  downloadUser,
  changeDateRange,
  deleteChildren,
  downloadFile,
  downloadFileFlow,
  downloadFileFlowPdf,
  tableRowClassName,
  GetDateDiff,
  divideMoney
}
export default common
